﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

using Swaf;
using Swaf.BizObj;
using Swaf.BizRule;
using Swaf.Container;
using Swaf.Security;
namespace Survey
{
    //public enum WizStepOptions { requiredBeforeCheckout = 0, optional = 1, mustCompleteBeforeMoveForward = 2 };
    //public IBizObj getArticleDetail(IApplication app, IRuleContext context
        //,object articleId,bool withTranslation,DetailLevel detailLevel, bool incrementCount, bool stripLeading)
    public class SurveyBizRule : Syrinx.BaseBizRules
    {
        
        public IBizObjList getCompanySurvey(IApplication app, IRuleContext context, INameAddressSupport info, IBizObj criteria)
		{
            try
            {
                IResults rc = app.ruleMgr.execute("getArticles", info, criteria);
                IBizObjList list = rc.CallResults as IBizObjList;


                
                return list;

            }
            catch (Exception e)
            {
                throw new SurveyException("error executing postExtendsGetSurveySettings", e);
            }
		}

        public IBizObjList GetUserSurveyResponses(IApplication app, IRuleContext context,string companyShortName)
        {
            try
            {
				FlexiMap m = new FlexiMap();
                IResults rc = app.ruleMgr.execute(context, "getArticleIdFromUniqueTitle", string.Format("Survey-{0}", companyShortName), null);
                if (rc.ExceptionInfo != null)
                    throw rc.ExceptionInfo;
                Swaf.BGuid.Guid id = rc.CallResults as Swaf.BGuid.Guid ;
                m.put("companyId", ActiveCompanyId);
                m.put("userId", CurrentUser.get("id"));
                m.put("parentId", id);
                return app.appData.get("DA.Survey.GetUserSurveyResponses", m) as IBizObjList;
            }
            catch (Exception e)
            {
                throw new SurveyException("error executing GetUserSurveyResponses", e);
            }
        }


        public IBizObj getUserFormData(IApplication app, IRuleContext context, Swaf.BGuid.Guid id)
        {
			FlexiMap m = new FlexiMap();
            m.put("userId", CurrentUser.get("id"));
            m.put("articleId", id);
            IBizObj response = app.appData.get("DA.Survey.GetUserSurveyResponse", m) as IBizObj;
            return response;
        }
        public IBizObj getSurveySettings(IApplication app, IRuleContext context, IBizObj survey)
        {
            if (survey != null)
            {
				FlexiMap m = new FlexiMap();
                m.put("id", survey.get("id"));
                IBizObj setting = app.appData.get("DA.Survey.GetSurveySetting", m) as IBizObj;
                if (setting != null)
                {
                    survey.put("minAnswer", setting.get("minAnswer"));
                    survey.put("maxAnswer", setting.get("maxAnswer"));
                }
            }
            return survey;
        }
        public void postExtendsUpdateSurveySettings(IApplication app, IRuleContext context, object returnValue, object[] inputParams)
        {
            if (inputParams != null && inputParams[2] !=null)
            {
                try
                {
                    IBizObj survey = inputParams[2] as IBizObj;
                    if (survey.containsField("minAnswer") && ((int)survey.get("minAnswer") > 0) || ((int)survey.get("maxAnswer") > 0))
                    {
						FlexiMap m = new FlexiMap();
                        m.put("id", survey.get("id"));
                        m.put("companyId", ActiveCompanyId);
                        m.put("minAnswer", survey.get("minAnswer"));
                        m.put("maxAnswer", survey.get("maxAnswer"));
                        app.appData.put("DA.Survey.DeleteSurveySettings", m);
                        app.appData.put("DA.Survey.InsertSurveySettings", m);
                    }
                }
                catch (Exception e)
                {
                    throw new SurveyException("error executing postExtendsUpdateSurveySettings.", e);
                }
            }
        }

        public void updateUserSurveyFormData(IApplication app, IRuleContext context, IBizObj artFormData)
        {
            try
            {
                IBizObj srvy = artFormData.get("article") as IBizObj;
                srvy = getSurveySettings(app, context, srvy);
                if (srvy != null)
                {
                    int min = (int)srvy.get("minAnswer");
                    int max = (int)srvy.get("maxAnswer");
                    int res = calcXmlFormData(artFormData);
                    string type = artFormData.get("type") as string;

                    

                    if (type.Equals("radio") && min > res)
                        throw new SurveyException(string.Format("{0}|{1}|{2}",SurveyException.ExceptionId.ANSWERISREQUIRED, min,artFormData.Xml));
                    else if (type.Equals("checkbox") || type.Equals("textarea"))
                    {
                        if(res > max)
                            throw new SurveyException(string.Format("{0}|{1}|{2}", SurveyException.ExceptionId.MAXIMUMANSWER, max,artFormData.Xml));
                        else if(res < min)
                            throw new SurveyException(string.Format("{0}|{1}|{2}", 
                               type.Equals("textarea") ? SurveyException.ExceptionId.REQUIREDLENGTH : SurveyException.ExceptionId.MINIMUMANSWER, min,artFormData.Xml));
                    }

                    //app.appData.put("DA.Articles.DeleteUserFormData", artFormData);
                    //context.RuleGroup.execute("updateUserArtFormData", null, "", new object[] { artFormData});

                    artFormData.put("user", CurrentUser);
                    artFormData.put("lastUpdated", DateTime.UtcNow);
                    app.appData.put("DA.Survey.AddUserSurveyResponse", artFormData);
					context.RuleGroup.executeAsync("notifyObservers", null, "", new object[] {
                        "ArtFormDataSubmited", artFormData});
                }
            }
            catch (SurveyException se)
            {
                throw se;
            }
            catch (Exception e)
            {
                throw new SurveyException("error executing updateUserArtFormData.", e);
            }

        }

        protected int calcXmlFormData(IBizObj artForm)
        {
            int result = 0;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(artForm.get("formData") as string);
            XmlElement root = doc.DocumentElement;
            if (root != null && root.Attributes.Count>0)
            {
                string type=root.Attributes[0].Value;
                artForm.put("type", type);
                for (int i = 1; i < root.Attributes.Count; i++)
                {
                    if (type == "radio")
                        result++;
                    else if (type == "checkbox" && root.Attributes[i].Value.ToLower().Equals("true"))
                        result++;
                    else if (type == "textarea")
                        result = root.Attributes[i].Value.ToString().Length;

                }
            }
            return result;
        }
    }
}
